package com.miaoda.miaoda_ai.aop;

import com.miaoda.miaoda_ai.annotation.AuthCheck;
import com.miaoda.miaoda_ai.exception.ErrorCode;
import com.miaoda.miaoda_ai.exception.ThrowUtils;
import com.miaoda.miaoda_ai.model.entity.User;
import com.miaoda.miaoda_ai.model.enums.UserRoleEnum;
import com.miaoda.miaoda_ai.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AuthInterceptor {


    @Resource
    private UserService userService;


    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String role = authCheck.mustRole();
        // 获取当前登录用户
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        User loginUser = userService.getLoginUser(request);

        // 不需要权限，放行
        UserRoleEnum enumByValue = UserRoleEnum.getEnumByValue(role);
        if (enumByValue == null) {
            return joinPoint.proceed();
        }
        // 需要权限
        String userRole = loginUser.getUserRole();

        if (userRole == null) {
            ThrowUtils.throwIf(true, ErrorCode.NO_AUTH_ERROR);
        }

        if (UserRoleEnum.ADMIN.equals(enumByValue) && !userRole.equals(enumByValue.getValue())) {
            ThrowUtils.throwIf(true, ErrorCode.NO_AUTH_ERROR);
        }
        // 有权限放行
        return joinPoint.proceed();
    }
}
